const mongoose = require('mongoose');

const GlucoseSchema = new mongoose.Schema(
  {
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true,
      index: true
    },
    value: {
      type: Number,
      required: true,
      min: [1.0, '血糖值不能低于1.0'],
      max: [33.3, '血糖值不能超过33.3']
    },
    unit: {
      type: String,
      enum: ['mmol/L', 'mg/dL'],
      default: 'mmol/L'
    },
    measuredAt: {
      type: Date,
      required: true,
      default: Date.now
    },
    category: {
      type: String,
      enum: ['空腹', '早餐前', '早餐后', '午餐前', '午餐后', '晚餐前', '晚餐后', '睡前', '凌晨', '随机'],
      required: true
    },
    notes: {
      type: String,
      maxlength: 500
    },
    tags: [String],
    isManualEntry: {
      type: Boolean,
      default: true
    },
    deviceInfo: {
      type: String
    },
    abnormal: {
      type: Boolean,
      default: false
    },
    abnormalReason: {
      type: String,
      enum: ['低血糖', '高血糖', '正常', ''],
      default: ''
    }
  },
  {
    timestamps: true
  }
);

// 创建复合索引，加速按用户和时间范围查询
GlucoseSchema.index({ user: 1, measuredAt: -1 });

// 在保存前计算是否为异常数据
GlucoseSchema.pre('save', function(next) {
  // 根据不同的测量类别，设置不同的正常范围
  let minNormal, maxNormal;
  
  if (['空腹', '早餐前', '午餐前', '晚餐前', '凌晨'].includes(this.category)) {
    // 餐前/空腹标准
    minNormal = 3.9; // mmol/L
    maxNormal = 7.2; // mmol/L
  } else {
    // 餐后标准
    minNormal = 3.9; // mmol/L
    maxNormal = 10.0; // mmol/L
  }
  
  // 转换单位如果是mg/dL
  if (this.unit === 'mg/dL') {
    // 将mg/dL转换为mmol/L进行比较
    // 1 mmol/L = 18 mg/dL
    const valueInMmol = this.value / 18;
    if (valueInMmol < minNormal) {
      this.abnormal = true;
      this.abnormalReason = '低血糖';
    } else if (valueInMmol > maxNormal) {
      this.abnormal = true;
      this.abnormalReason = '高血糖';
    } else {
      this.abnormal = false;
      this.abnormalReason = '正常';
    }
  } else {
    // 已经是mmol/L单位
    if (this.value < minNormal) {
      this.abnormal = true;
      this.abnormalReason = '低血糖';
    } else if (this.value > maxNormal) {
      this.abnormal = true;
      this.abnormalReason = '高血糖';
    } else {
      this.abnormal = false;
      this.abnormalReason = '正常';
    }
  }
  
  next();
});

module.exports = mongoose.model('Glucose', GlucoseSchema); 